package com.ruoyi.web.core.config;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * restTemplate的配置
 */
public class RestTemplateUtil {
    public static RestTemplate restTemplate;
    public static final Logger log = LoggerFactory.getLogger(RestTemplateUtil.class);
    private RestTemplateUtil(){}
    static {
        NoSSL factory = new NoSSL();
        factory.setReadTimeout(50000000);
        factory.setConnectTimeout(1500000000);//单位为ms
        factory.setOutputStreaming(false);
        restTemplate = new RestTemplate(factory);
        //http code 非 200 处理机制
        restTemplate.setErrorHandler(new ResponseErrorHandler() {
            @Override
            public boolean hasError(ClientHttpResponse clientHttpResponse) throws IOException {
                return true;
            }

            @Override
            public void handleError(ClientHttpResponse clientHttpResponse) throws IOException {
            }
        });
        List<HttpMessageConverter<?>> list = restTemplate.getMessageConverters();
        for (HttpMessageConverter<?> httpMessageConverter : list) {
            if (httpMessageConverter instanceof StringHttpMessageConverter) {
                ((StringHttpMessageConverter) httpMessageConverter).setDefaultCharset(StandardCharsets.UTF_8);
                break;
            }
        }
    }

    public static  JSONObject questHttp(String url, Map<String,Object> map, String description) throws Exception {
        String httpUrls = url;
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<Object> httpEntity = new HttpEntity<Object>(JSONObject.toJSONString(map),headers);
        ResponseEntity<String> stringResponseEntity = null;
        try {
            stringResponseEntity = restTemplate.postForEntity(httpUrls, httpEntity, String.class);
        } catch (Exception e) {
            log.error(description+"异常,报错信息为:"+e.getMessage());
            throw new Exception(description+"异常,报错信息为:"+e.getMessage());
        }
        if (stringResponseEntity.getStatusCodeValue() != HttpStatus.OK.value()) {
            log.error(description+"报错");
        }
        JSONObject data = JSON.parseObject(stringResponseEntity.getBody());
        return data;
    }

    public static JSONObject getGpsToken(String gpsurl) throws Exception {
        Map<String,Object> map=new HashMap<String, Object>();
        map.put("busiCode","memberLogin");
        JSONObject json=new JSONObject();
        json.put("username","测试3");
        json.put("password","123456");
        json.put("uuid","");
        json.put("loginType","1");
        map.put("body",json);
        JSONObject resultJson= RestTemplateUtil.questHttp(gpsurl,map,"GPS登录获取token接口");
        JSONObject dataStr=JSON.parseObject(resultJson.getString("data"));
        return dataStr;
    }

    public static JSONObject getGpsTokenByUser(String gpsurl, String userName, String password) throws Exception {
        Map<String,Object> map=new HashMap<String, Object>();
        map.put("busiCode","memberLogin");
        JSONObject json=new JSONObject();
        json.put("username",userName);
        json.put("password",password);
        json.put("uuid","");
        json.put("loginType","1");
        map.put("body",json);
        JSONObject resultJson= RestTemplateUtil.questHttp(gpsurl,map,"GPS登录获取token接口");
        JSONObject dataStr=JSON.parseObject(resultJson.getString("data"));
        return dataStr;
    }

    public static JSONObject getLocByDeviceImeis(String gpsurl,String deviceImeis) throws Exception {
        Map<String,Object> map=new HashMap<String, Object>();
        map.put("busiCode","locationMulti");
        JSONObject json=new JSONObject();
        json.put("device_imeis",deviceImeis);
        map.put("body",json);
        map.put("x_token",getGpsToken(gpsurl).getString("x_token"));
        JSONObject resultJson= RestTemplateUtil.questHttp(gpsurl,map,"GPS登录获取token接口");
        JSONArray jsonArray=resultJson.getJSONArray("data");
        JSONObject resultObj=new JSONObject();
        for(Object mapList : jsonArray){
            for (Object entry : ((Map)mapList).entrySet()){
                resultObj.put("baidu_lng",((Map<?, ?>) mapList).get("baidu_lng"));
                resultObj.put("baidu_lat",((Map<?, ?>) mapList).get("baidu_lat"));
            }
        }
       return  resultObj;
    }

    public static JSONArray getDeviceList(String gpsurl) throws Exception {
        Map<String,Object> map=new HashMap<String, Object>();
        map.put("busiCode","deviceList");
        JSONObject json=new JSONObject();
        json.put("global_status","-2");
        json.put("member_id",getGpsToken(gpsurl).getString("member_id"));
        map.put("body",json);
        map.put("x_token",getGpsToken(gpsurl).getString("x_token"));
        JSONObject resultJson= RestTemplateUtil.questHttp(gpsurl,map,"获取设备列表接口");
        JSONArray jsonArray=resultJson.getJSONArray("data");
        return  jsonArray;
    }



    public static void main(String[] args) throws Exception {
        getLocByDeviceImeis("https://apiss.bfgps.net.cn/wxapi/api","868120303700501");
    }
}
